<script setup lang="ts">
import { type FormInstance, Message } from '@arco-design/web-vue'
import OrgTreeSelect from './OrgTreeSelect.vue'
import { OrgApi } from '@/apis'
import { useConfirm, useForm } from '@/hooks'
import * as Regexp from '@/utils/regexp'

// 保存
const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const readonly = ref(true)

const dataId = ref('')
const dataDetail = ref<OrgApi.OrgDetailResp>()
const formRef = ref<FormInstance>()
const { form, resetForm } = useForm({
  id: null,
  name: null,
  shortName: null,
  code: null,
  parentId: null,
  leaderId: null,
  orgType: null,
  status: null,
})
const rules: FormInstance['rules'] = {
  parentId: [{ required: true, message: '请选择上级组织' }],
  name: [{ required: true, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线，长度为2-32位' }],
  shortName: [{ required: false, match: Regexp.Name, message: '名称只能含有中文、数字、英文、下划线、短横线，长度为2-32位' }],
  code: [{ required: false, match: Regexp.Code, message: '编码只能含有英文、数字、下划线、短横线，以字母开头，长度为2-32位' }],
}
// 重置
const reset = () => {
  formRef.value?.resetFields()
  resetForm()
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 删除
const onDelete = () => {
  useConfirm(() => OrgApi.remove(dataId.value), () => {
    emit('change')
    visible.value = false
  })
}

// 取消
const onCancel = () => {
  readonly.value = true
  // Object.assign(form, dataDetail.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

// 保存
const onSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) {
    return false
  }
  await OrgApi.update(form, dataId.value)
  Message.success('修改成功')
  emit('change')
  visible.value = false
}

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await OrgApi.getDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

// 打开面板
const open = async (id: string) => {
  dataId.value = id
  loading.value = true
  visible.value = true
  readonly.value = true
  getDataDetail()
}

defineExpose({ open })
</script>

<template>
  <ProDrawer
    v-model:visible="visible"
    :loading="loading"
    :title="dataDetail?.name || '组织详情'"
    :footer="false"
    @before-ok="onSave"
    @close="reset"
  >
    <a-card title="基础信息" class="section">
      <template #extra>
        <ReadonlyEditButton
          :readonly="readonly"
          @delete="onDelete"
          @edit="onEdit"
          @cancel="onCancel"
          @save="onSave"
        />
      </template>
      <a-form ref="formRef" layout="vertical" :model="form" :rules :readonly size="medium">
        <a-row :gutter="28">
          <readonly-form-item label="组织类型" field="orgType">
            <DictSelect v-model="form.orgType" code="OrgTypeEnum" type="button" />
          </readonly-form-item>
          <readonly-form-item label="状态" field="status">
            <DictSelect v-model="form.status" code="CommonStatusEnum" type="switch" />
            <template #readonly>
              <CellStatus :status="dataDetail?.status" />
            </template>
          </readonly-form-item>
          <readonly-form-item v-if="form.parentId" label="上级组织" field="parentId" :span="24">
            <OrgTreeSelect v-model.trim="form.parentId" />
            <template #readonly>
              <a-tag>{{ dataDetail?.parentOrgName }}</a-tag>
            </template>
          </readonly-form-item>
          <readonly-form-item label="名称" field="name" :span="24">
            <a-input v-model.trim="form.name" placeholder="请输入名称" :max-length="32" show-word-limit />
          </readonly-form-item>
          <readonly-form-item label="简称" field="shortName">
            <a-input v-model.trim="form.shortName" placeholder="请输入简称" :max-length="32" />
          </readonly-form-item>
          <readonly-form-item label="组织编码" field="code">
            <a-input v-model.trim="form.code" placeholder="请输入编码" :max-length="32" />
          </readonly-form-item>
          <readonly-form-item label="负责人" field="leaderId">
            <EmployeeSelect v-model.trim="form.leaderId" />
            <template #readonly>
              <a-tag>{{ dataDetail?.leaderName || '--' }}</a-tag>
            </template>
          </readonly-form-item>
          <readonly-form-item label="联系电话" field="telephone">
            <a-input v-model.trim="form.telephone" placeholder="请输入电话号码" :max-length="32" />
          </readonly-form-item>
          <readonly-form-item label="地址" field="address" :span="24">
            <a-textarea v-model.trim="form.address" placeholder="请输入地址" :max-length="128" show-word-limit />
          </readonly-form-item>
        </a-row>
      </a-form>
    </a-card>
  </ProDrawer>
</template>

<style lang="less" scoped></style>
